package com.groupbuying.payconsumer.utils;

import org.apache.commons.lang3.StringUtils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author gxy
 * @Description map转bean，bean转map工具类
 * @Date 2019/1/10 11:23
 **/
public class BeanOrMapConvertUtils {

    public static Map<String, Object> objectToMap(Object obj) throws Exception {
        if(obj == null){
            return null;
        }

        Map<String, Object> map = new HashMap<String, Object>();

        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            map.put(field.getName(), field.get(obj));
        }

        return map;
    }

    public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
        if (map == null)
            return null;
        Object obj = beanClass.newInstance();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            int mod = field.getModifiers();
            if(Modifier.isStatic(mod) || Modifier.isFinal(mod)){
                continue;
            }

            field.setAccessible(true);
            field.set(obj, map.get(field.getName()));
        }

        return obj;
    }

    /**
     * Map转Bean(泛型)
     * @param map
     * @param beanType
     * @param <T>
     * @return
     */
    public static <T>T map2bean(Map<String, Object> map, Class<?> beanType) {
        if (map == null)
            return null;
        Object ret = null;
        try{
            //创建bean对象
            ret = beanType.newInstance();
            BeanInfo beanInfo= Introspector.getBeanInfo(beanType,Object.class);
            PropertyDescriptor[] pds=beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor pd:pds){
                //从map中获取和属性同名的key的值
                Object value=map.get(humpToUnderline(pd.getName()));
                //调用setter方法，设置属性值。
                if (value != null){
                    pd.getWriteMethod().invoke(ret,value);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return (T)ret;

    }



    /***
     * 驼峰命名转为下划线命名
     * @param para 驼峰命名的字符串
     */

    public static String humpToUnderline(String para){
        StringBuilder sb=new StringBuilder(para);
        if(StringUtils.isEmpty(para)){
            return "";
        }
        //定位
        int temp = 0;
        if (!para.contains("_")) {
            for(int i=0;i<para.length();i++){
                if(Character.isUpperCase(para.charAt(i))){
                    sb.insert(i+temp, "_");
                    temp+=1;
                }
            }
        }
        return sb.toString().toLowerCase();
    }

}
